package cn.school.web;

import cn.school.entity.*;
import cn.school.service.GradeService;
import cn.school.service.StudentService;
import cn.school.util.StringKit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;

// loginServlet X
// login.do
//  update.do
//  admin/login.do ?
@WebServlet(name = "MainServlet",value = "*.do")//*.cmd
public class MainServlet extends HttpServlet {

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("username");
        String pass=request.getParameter("pass");

        if(name.startsWith("java62")&&pass.equals("123456")){
            request.getSession().setAttribute("USER_LOGIN",name);
            response.sendRedirect("success.jsp");
            return;
        }
        request.setAttribute("msg","用户名或者密码错误");
        request.getRequestDispatcher("/adminLogin.jsp").forward(request,response);
    }
//    protected Student findStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//       long stuno= StringKit.toLong(request.getParameter("stuno"));
//       return service.get(stuno);//null
//    }
protected AjaxResult findStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    long stuno= StringKit.toLong(request.getParameter("stuno"));
    Student s= service.get(stuno);//null
    if(s!=null)
        return AjaxResult.success(s);

    return AjaxResult.error("对象不存在");
}

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("删除功能没有实现");
    }
    StudentService service=new StudentService();
    protected Page<Student> studentSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //java.io.OutputStream out=response.getOutputStream();

        int pageNo=1;
        try{
            pageNo=Integer.parseInt(request.getParameter("page"));
        }catch(Exception e){}
        int limit=Page.PAGE_SIZE;
        try{
            limit=Integer.parseInt(request.getParameter("limit"));
        }catch(Exception e){}

        String name=request.getParameter("sname");
        name=name==null?"":name;
        String tel=request.getParameter("tel");
        tel=tel==null?"":tel;

        Date start=StringKit.toDate(request.getParameter("start"));
        Date end=StringKit.toDate(request.getParameter("end"));

        Page<Student> p=service.search(pageNo, limit, name, tel, start, end);

        return p;
    }
//    protected Page2<Student> studentSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
//        int pageNo=1;
//        try{
//            pageNo=Integer.parseInt(request.getParameter("pageNo"));
//        }catch(Exception e){}
//        String name=request.getParameter("sname");
//        name=name==null?"":name;
//        String tel=request.getParameter("tel");
//        tel=tel==null?"":tel;
//
//        Page2<Student> p=service.search(pageNo, StudentService.PAGE_SIZE, name, tel, null, null);
//
//        return p;
//    }

    GradeService gradeService=new GradeService();
    protected Page<Grade> gradesearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo=StringKit.toInt(request.getParameter("page"),1);
        int pageSize=StringKit.toInt(request.getParameter("limit"),5);
        String gname=request.getParameter("gname");
        return gradeService.search(pageNo,pageSize,gname);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
//        out.print("<html>");
//        out.print("<body>");
//        out.print("<h1>contextpath:"+request.getContextPath()+"</h1>");
//        out.print("<h1>servletpath:"+request.getServletPath()+"</h1>");
//        out.print("<h1>uri:"+request.getRequestURI()+"</h1>");
//        out.print("<h1>url:"+request.getRequestURL()+"</h1>");
//        out.print("<h1>querystring:"+request.getQueryString()+"</h1>");
        String p=request.getServletPath();// /login.do
        p=p.substring(1,p.length()-3);  //   login
        if(p.equals("service")||p.equals("doGet")||p.equals("doPost")){
            response.sendError(403,"禁止此请求方法");
            return;
        }
        try {
            Method m=this.getClass().getDeclaredMethod(p,HttpServletRequest.class,HttpServletResponse.class);
            Object o=m.invoke(this,request,response);
            if(o!=null){//把o转换成json,发给客户端
                response.setContentType("application/json;charset=utf-8");
                String str= JSON.toJSONStringWithDateFormat(o,"yyyy-MM-dd", SerializerFeature.WriteMapNullValue,
                        SerializerFeature.WriteDateUseDateFormat);//, SerializerFeature.UseISO8601DateFormat);
                response.getWriter().print(str);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            response.sendError(403,"没有这个请求方法");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(404,"请求出错："+e);
        }


//        if(p.equals("login")){
//            out.print("<h2 style='color:red;'>这是登录</h2>");
//            login(request,response);
//        }else if(p.equals("update")){
//            out.print("<h2 style='color:red;'>这是更新</h2>");
//            update(request,response);
//        }else if(p.equals("del")){
//            out.print("<h2 style='color:red;'>这是删除</h2>");
//            del(request,response);
//        }else{
//            out.print("<h2 style='color:red;'>未知操作</h2>");
//        }//反射
//        out.print("</body>");
//        out.print("</html>");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
